package atguigu2.assist;

import java.util.Arrays;
import java.util.concurrent.FutureTask;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/4
 * @VERSION 1.0
 * @DESC
 * CountDownLatch: 计数器  -- 资源计数变量？
 * 基本步骤：创建，定义初始值； 减一； 等待直到为0
 *
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建
//        CountDownLatch countDownLatch = new CountDownLatch(6);
//
//        for (int i = 1; i <= 6; i++) {
//            new Thread(()->{
//                System.out.println(Thread.currentThread().getName()+"离开教室...");
//                countDownLatch.countDown();
//            },"Thread-"+i).start();
//        }
//        countDownLatch.await();//InterruptedException 阻塞可能被打断
//        System.out.println(Thread.currentThread().getName()+"关门");

        // 采用callable?

        FutureTask<Boolean>[] futureTasks = new FutureTask[6];
        //List<FutureTask<Boolean>> futureTaskList =new ArrayList<>();
        for (int i = 1; i <= 6 ; i++) {
            futureTasks[i-1] = new FutureTask<>(()-> {
                System.out.println(Thread.currentThread().getName() + "离开教室...");
                return true;
            });
            new Thread(futureTasks[i-1],"Thread-"+i).start();//
//            futureTaskList.add(new FutureTask<>(()-> {
//                System.out.println(Thread.currentThread().getName() + "离开教室...");
//                return true;
//            }));
//            new Thread(futureTaskList.get(i-1),"Thread-"+i).start();//futureTasks[i-1]
        }

        boolean [] flags = new boolean[6];
        int success = 0;
        Arrays.fill(flags,false);
        while (success<6){
            for (int i = 0; i < 6; i++) {
                if(flags[i]==false&&futureTasks[i].isDone()){
                    success++;
                    flags[i]=true;
                }
            }
        }


//        while(!futureTaskList.isEmpty()){
//            for (FutureTask<Boolean> futureTask:futureTaskList) {
//                if(futureTask.isDone()){
//                    futureTaskList.remove(futureTask);
//                }
//            }
//        }
        System.out.println("关门");






    }
}
